<template>
  <div class="goods-detail">
    <div class="fixedTop">
      <headBar  isBack="show" class="head">
        <div slot="xm-header-center">
          <div class="xm-header-title">
            <span @click="toTab('goods',1)" :class="{'active': tab==1}">商品</span>
            <span @click="toTab('detail',2)" :class="{'active': tab==2}">详情</span>
            <span @click="toTab('guige',3)" :class="{'active': tab==3}">规格</span>
          </div>
        </div>
        <div slot="xm-header-right"></div>
      </headBar>
    </div>
    <section v-show="tab==1">
      <mt-swipe class="xm-swipe bg-white" ref="goods" id="goods" :auto="4000">
        <mt-swipe-item v-for="item in goodsDetail.images">
          <div class="bg-img1" :style="item"></div>
        </mt-swipe-item>
      </mt-swipe>
      <div class="goods-page">
      <section class="goods-group border-1px bg-white">
        <h3 class="text-ellipsis">
          <em class="icon tag bg" v-show="goodsDetail.supplierInfo.supplierTypeId==1">自营</em>
          {{goodsDetail.name || ''}}
        </h3>
        <p class="text-line2">{{goodsDetail.wareDes || ''}}</p>

        <div class="flex flex-pack-justify goods-price bg-white">
          <span class="price"><em>￥</em>{{goodsDetail.pricePiece || 0 | money}}<em>/件</em></span>
          <span>件规: {{goodsDetail.numberPerBox}} <em>{{goodsDetail.unitName}}</em></span>
          <span>单价: ￥{{goodsDetail.priceUnit | money}}</span>
        </div>
      </section>
      <section class="sale-group bg-white">
        <div v-show="goodsDetail.openPresale==1"><em class="icon tag">可预售</em>商品无库存也可以下单</div>
        <div v-show="goodsDetail.pandaCoinNum!=-1"><em class="icon tag">熊猫币</em>购买商品赠{{goodsDetail.pandaCoinNum}}熊猫币/件 <span class="help" @click="isPandaBi=true"></span></div>
      </section>
      <!---->
      <section class="stock-group border-1px bg-white">
        <div class="flex flex-pack-justify item">
          <span><em class="title">库存量：</em> {{goodsDetail.numberInventory}}件 <em class="icon tag" v-show="goodsDetail.numberInventory<=0">有现货</em></span>
          <span><em class="title">销量：</em> {{goodsDetail.wareCount}}件</span>
        </div>
        <div class="flex flex-pack-justify item">
          <span><em class="title">起批量：</em> {{goodsDetail.numberWholesale}}件</span>
          <span><em class="title">发货地：</em> {{goodsDetail.sendAddress}}</span>
        </div>
      </section>

      <section class="attr-group flex flex-pack-justify bg-white" @click="isAttr=true" v-show="hasAttr">
        <span>属性</span>
        <div><span class="attr-name">{{goodsDetail.wareAttrName}}</span><span class="icon icon-arrowright"></span></div>
      </section>

      <section class="store-group flex flex-pack-justify bg-white" @click.stop="enterStore(goodsDetail.supplierInfo.supplierId)">
        <div class="flex-1">
          <div class="store-name"><i class="icon icon-dianpu5"></i>{{goodsDetail.supplierInfo.supplierName}}</div>
          <div class="store-sale">主营：{{goodsDetail.supplierInfo.mainBiz}}</div>
        </div>
        <div class="icon icon-arrowright"></div>
      </section>
    </div>
    </section>
    <div class="img-page" ref="detail" id="detail" v-show="tab==2">
      <section>
        <div class="detail-img">
          <img src="../../assets/images/ad/ad-1.jpg" alt="">
          <img src="../../assets/images/ad/ad-2.jpg" alt="">
          <img src="../../assets/images/ad/ad-1.jpg" alt="">
          <img src="../../assets/images/ad/ad-2.jpg" alt="">
        </div>
        <!--<div class="detail-img"  v-html="goodsDetail.description">-->
        <!--</div>-->
      </section>
    </div>

    <!--规格参数-->
    <div class="detail-page" ref="guige" id="guige" v-show="tab==3">
      <div class="detail-size" >
        <dl>
          <dd>
            <span>商品编号</span>
            <span>{{goodsDetail.id || '未知'}}</span>
          </dd>
          <dd>
            <span>生产许可证</span>
            <span>{{goodsDetail.productionLicense || '未知'}}</span>
          </dd>
          <dd>
            <span>执行标准</span>
            <span>{{goodsDetail.performStandard || '未知'}}</span>
          </dd>
          <dd>
            <span>厂名</span>
            <span>{{goodsDetail.manufacturer || '未知'}}</span>
          </dd>
          <dd>
            <span>保质期</span>
            <span>{{goodsDetail.shelfLife || '未知'}}</span>
          </dd>
          <dd>
            <span>存储方式</span>
            <span>{{goodsDetail.method || '未知'}}</span>
          </dd>
          <dd>
            <span>包装方式</span>
            <span>{{goodsDetail.methodPacking || '未知'}}</span>
          </dd>
          <dd>
            <span>生产日期</span>
            <span>见包装封口处</span>
          </dd>
          <dd>
            <span>产地</span>
            <span>{{goodsDetail.manufacturerAddress || '未知'}}</span>
          </dd>
          <dd>
            <span>件装尺寸规格</span>
            <span>{{goodsDetail.sizePiece || '未知'}}</span>
          </dd>
        </dl>
      </div>
    </div>

    <!--属性-->
    <div class="fade" v-show="isAttr"></div>
    <div class="attr-list" v-show="isAttr">
      <div class="head border-bottom">
        <span>选择属性</span>
        <em class="close" @click="isAttr=false"></em>
      </div>
      <div class="list flex flex-pack-center flex-wrap">
        <span  class="text-ellipsis" :class="{active: item.active}" v-for="item in goodsDetail.wareAttrList" @click="detail(item)">{{item.name}}</span>
        <span style="visibility: hidden"></span>
        <span style="visibility: hidden"></span>
      </div>
    </div>

    <div class="foot-blank"></div>
    <div class="xm-footer">
      <div class="flex flex-pack-justify  flex-align-center">
        <a href="javascript:;" class="shoucang" @click="favorites" :class="{'red-color' : isFavorite }">
          <i class="icon icon-shoucang"></i>
          <p v-show="isFavorite">已收藏</p>
          <p v-show="!isFavorite">收藏</p>
        </a>
        <router-link  to="/purchase/list" class="flex-1 purchase_d" >
          <i class="icon purchase"><em class="num" v-show="purchaseNum>0">{{purchaseNum}}</em></i>
          <p>采购单</p>
        </router-link>
        <a href="javascript:;" class="btn1 join" :class="{'bg-gray': !isJoin}" @click="addPurchase">
          加入采购单
        </a>
      </div>
    </div>

    <!--加入采购单-->
    <div class="alert-box" v-show="isAddPurchase">
      <div class="fade" @click.stop="isAddPurchase=false"></div>
      <div class="address-group">
        <div class="head">
          <em class="close" @click.stop="isAddPurchase=false"></em>
          <div class="flex">
            <img class="border-1px" :src="goodsDetail.imageThumb">
            <div class="goods-info flex-1">
              <div class="flex goods-name"><em class="icon tag">自营</em><span class="text-ellipsis">{{goodsDetail.name || '商品名'}}</span></div>
              <priceShow class="red-color" :price="goodsDetail.pricePiece" :unitName="goodsDetail.unitName"></priceShow>
            </div>
          </div>
        </div>
        <div class="address-list">
          <div class="item flex flex-align-center" v-for="item in addressList">
          <span class="icon flex-1 select" :class="{selected : item.isChecked}" @click="selectAddress(item)">
            {{item.provinceName + item.cityName + item.address | filterAddress}}
          </span>
          <div class="num-div">
            <span  @click="numMinus(item)">-</span><span class="num">{{item.num}}</span><span @click="numPlus(item)">+</span>
          </div>
          <div class="opts-num border-1px hide">
            <span class="border-right" @click="numMinus(item)">-</span>
            <span class="num border-right" :text="item.num">{{item.num}}</span>
            <span @click="numPlus(item)">+</span>
          </div>
          </div>
          <div class="add" @click="addAddressFun">+ 建议收货地址</div>
        </div>
        <div class="opts flex">
          <div class="flex-1 bg-white select-all">
            <em class="icon select" :class="{selected : checkAll}" @click="selectAll">全选</em>
            <i>({{checkedNum}} / {{addressList.length}})</i>
          </div>
          <div class="flex-1 btn" :class="{active : checkedNum>0}"  @click="addPurchaseOrder">
            确认采购
            <priceShow :price="goodsDetail.pricePiece*goodsNum" unitName="" v-show="checkedNum>0"></priceShow>
          </div>
        </div>
      </div>
    </div>
    <!--添加地址-->
    <addAddress v-show="isShowAddr"></addAddress>

    <pandaBi v-show="isPandaBi"></pandaBi>

    <xm-loading v-show="loading"></xm-loading>
  </div>
</template>
<script>
  import purchase from '../purchase/purchase.vue'
  import addAddress from '../address/add.vue'
  export default {
    props: {
    },
    data() {
      return {
        purchaseNum:0,
        isPandaBi:false,
        tab: 1,
        isAddPurchase:false,
        isShowAddr:false,
        isAttr: false,
        isFavorite: false,
        goodsId: '',
        showPrice: Cookie.get('showPrice')!=0,
        auditStatus: Cookie.get('auditStatus'),
        goodsDetail: {
            supplierInfo:{}
        },
        addressList:[],
        checkAll:true,
        checkedNum:0,
        goodsNum: 0, //购买商品数量
        favoritesId: null, //收藏id
        isVip: false, //是否为会员
        isLogin: !!Cookie.get('name'),
        hasAttr: true,
        loading: true,
        isJoin: false //是否可以加入采购单
      }
    },
    methods: {
      //获取商品详情
      getWareDetail(){
        getWareDetail({id: this.goodsId}).then(data=>{
          this.loading = false;
          if(data.returnCode == '000000'){
              let images =  [];
              data.result.imageMain =  data.result.imageMain? data.result.imageMain.split(','):[];
              data.result.imageMain.forEach(item=>{
                if(item!=''){
                    images.push({backgroundImage: 'url(' + item + ')'});
                }
            })
              data.result.images = images;
              this.goodsDetail = data.result;
            if(data.result.wareAttrList.length > 0){
              this.hasAttr = true;
            }
            let numberWholesale = this.goodsDetail.numberWholesale;
            let wareCount = this.goodsDetail.numberInventory;
            if(this.goodsDetail.openPresale ==1 || (wareCount != 0 && wareCount >= numberWholesale)){
              this.isJoin = true;
            }
          }
        })
      },
      //采购单数据
      pruchaseNum(){
          pruchaseNum().then(data=>{
              if(data.returnCode == '000000'){
                  this.purchaseNum = data.result.pruchaseNum;
              }
          })
      },
      //收藏
      favorites(){
        if(this.isFavorite){
          this.cancelFavorites();
          return;
        }
        favorites({wareId: this.goodsId}).then(data=>{
          if(data.returnCode == '000000'){
            this.isFavorite = true;
            this.favoritesId = data.result.id;
            Toast('收藏成功');
          }else if(data.returnCode == '100003'){
            this.$router.push({name: 'login'});
          }else{
            Toast(data.errorMsg);
          }
        })
      },
      // 取消收藏
      cancelFavorites(){
        cancelFavorites({id: this.favoritesId}).then(data=>{
          if(data.returnCode == '000000'){
            this.isFavorite = false;
            this.favoritesId = null;
            Toast('取消收藏成功');
          }else{
            Toast(data.errorMsg);
          }
        })
      },
      //获取收藏状态
      getFavoritesStatus(){
        getFavoritesStatus({wareId: this.goodsId}).then(data=>{
          if(data.returnCode == '000000'&& data.result.favoritesId){
            this.isFavorite = true;
            this.favoritesId = data.result.favoritesId;
          }
        });
      },
      /**
       * 加入购物车
       * @param <number> 商品id
       * */
      addPurchase(){
        if(!this.isJoin)return;
        this.isAddPurchase=true;
        this.getAddressList();
//      this.$router.push({name: 'purchase', params: {goodId: this.goodsId}});
      },
      /**
       * 点击属性打开商品详情
       * @param <object> 商品属性
       * */
      detail(item){
        this.$set(item, 'active', true);
        this.$router.push({name: 'goodsDetail', params: {wareId: item.wareId}});
        location.reload();
      },
      /*tab到指定位置*/
      toTab(str,index){
          this.tab=index;
          var pos1=this.$refs.goods.position;
          document.body.scrollTop =0;
      },
      // 进入商店
      enterStore: function(supplierId){
        this.$router.push({name: 'store', params: {storeId: supplierId}});
      },
      //获取地址列表
      getAddressList(){
          getAddressList().then(data=>{
              this.loading = false;
              if(data.returnCode == '000000'){
                  this.addressList = data.result.buyerAddressList;
                  this.hasAddress = this.addressList.length > 0;
                  [].forEach.call(this.addressList, item =>{
                      this.$set(item,'isChecked',true);
                      this.$set(item,'num', this.goodsDetail.numberWholesale || 1);
                      console.log(this.goodsDetail)
                  });
                  setTimeout(()=>{
                      this.compute();
                  }, 20);
              }
          })
      },
      numMinus(item){
          if(!item.num){
              this.$set(item, 'num',1 );
          }
          if(item.num > (this.goodsDetail.numberWholesale || 1)){
              item.num--;
              this.$set(item, 'num',item.num);
          }
          this.$nextTick(()=>{
              this.compute();
          })
      },
      numPlus(item){
          if(!item.num){
              this.$set(item, 'num', 1);
          }
          item.num++;
          if(item.num > 9999){
              item.num = 9999;
          }
          this.$set(item, 'num', item.num);
          this.$nextTick(()=>{
              this.compute();
          })
      },
      //全部选中
      selectAll(){
          this.checkAll=!this.checkAll;
          [].forEach.call(this.addressList, (select)=>{
              select.isChecked = this.checkAll;
          });
          this.compute();
      },
      //勾选单个地址
      selectAddress(el){
          el.isChecked=!el.isChecked;
          this.isCheckedAll();
          this.compute();
      },
      //计算商品数量
      compute(){
          var checkedArr=[];
          this.checkedNum=0;
          this.goodsNum = 0;
          [].forEach.call(this.addressList, (select)=>{
              if(select.isChecked){
                  checkedArr.push(select);
                  this.checkedNum+=1;
                  this.goodsNum += parseInt(select.num) || 1;
              }
          });
          if(checkedArr.length<this.addressList.length){
              this.checkAll=false;
          }else {
              this.checkAll=true;
          }
      },
      /*全选是否选中*/
      isCheckedAll(){
          var checkedArr=[];
          [].forEach.call(this.addressList, (select)=>{
              if(select.isChecked){
                  checkedArr.push(select);
              }
          });
          if(checkedArr.length<this.addressList.length){
              this.checkAll=false;
          }else {
              this.checkAll=true;
          }
      },
      /**
       * 添加订单
       * @param <bool> 是否继续购物 ，true 继续购物
       * */
      addPurchaseOrder(){
          let receivingList = [];
          [].forEach.call(this.addressList, (select)=> {
              if (select.isChecked) {
                  let receivingId = select.id;
                  let num = select.num || 1;
                  receivingList.push({receivingId: receivingId, number: num });
              }
          });
          if(receivingList.length == 0){
//                Toast('收货地址不能为空');
              return;
          }
          let params = {
              wareId: this.goodsId,
              receivingList: receivingList
          }
          addPurchaseOrder(params).then(data=>{
              if(data.returnCode == '000000'){
                  this.$router.push({name: 'purchaseList'});
              }else{
                  Toast(data.errorMsg);
              }
          })
      },
      //添加收货地址
      addAddressFun(){
          this.isAddPurchase=false;
          this.isShowAddr=true;
      },
    },
    created() {
      document.body.scrollTop = 0;
      this.goodsId = this.$route.params['wareId'];
      this.getWareDetail();
      this.getFavoritesStatus();
      this.pruchaseNum();
    },
    mounted(){

    },
    components: {
        purchase,
        addAddress
    }
  };
</script>
<style lang="less" scoped>
  @import "./detail.less";
  .fixedTop{
    height: .88rem;
  }
  .alert-box{
    position: fixed;
    width: 100%;
    height: 100%;
    top:0;
    z-index: 10;
  }
  .em.icon.tag.bg{
    border-radius: 6px;
  }
  .goods-detail .xm-footer .shoucang{
    width: 1rem;
    padding: 0 0 0 .9rem ;
  }
  .goods-detail .xm-footer .shoucang i{
    width: auto;
    height: auto;
    padding:.2rem 0 .2rem;
    font-size: .36rem;
  }
</style>
